//
// Copyright 2010 Yu Jianrong, All Rights Reserved
// 
// Licensed under BSD License.


// special case, remove iframe of dm5 page (not include the comic page)
if (window.location.host==="www.dm5.com" && !(/^\/Comic\//.test(window.location.pathname)))
{
    var ifs=document.getElementsByTagName("iframe");
    for(var i=ifs.length-1; i>=0; --i)
        ifs[i].parentNode.removeChild(ifs[i]);
}
else
(function()
{
    var $_=function(id)
    {
        return document.getElementById(id);
    };
    var m=document.createElement("meta");
    m.name="viewport";
    div_imgs=[];
    var VerticalWritting = true;
    var Landscape= false;

    var getPageURL=function(thePage) { return window.location.href; }
    var div_postprocess = function(){};

    if (window.location.host.indexOf("dm5.com")!==-1)
    {
        var getCurrentPage=function()
        {
            return page;
        }
        var getPageCount=function()
        {
            return array_img.length-1;
        }
        var getImgURL=function(thePage)
        {
            page=thePage;
            array_img=desMe();
            return uncMe(array_img[page]);
        }
        var setCurrentPage=function(thePage)
        {
            page = thePage;
        }
        getPageURL = function(thePage)
        {
            var nowurl=new String(window.location.href);
            if(nowurl.indexOf("_page")>-1)
                nowurl=nowurl.substring(0,nowurl.indexOf("_page"));
            else if(nowurl.indexOf(".htm")>-1)
                nowurl=nowurl.substring(0,nowurl.indexOf(".htm"));
            nowurl += '_page-'+(thePage+1)+'.htm';
            return nowurl;
        }
    }else if (window.location.host.indexOf("u17.com")!==-1)
    {
        VerticalWritting = false;

        var getCurrentPage=function()
        {
            return c_page;
        }
        var getPageCount=function()
        {
            return __htmlURL.length;
        }
        var getImgURL=function(thePage)
        {
            var url=__htmlURL[thePage];
            //get the html
            var request = new XMLHttpRequest();
            request.open("GET", url, false);
            request.send();
            request.responseText;
            return /src="([^"]*)"/.exec(eee(/document.write\(eee\('([^']*)'/.exec(request.responseText)[1]))[1];
        }
        var setCurrentPage=function(thePage)
        {
            c_page=thePage;
        }
        getPageURL = function(thePage)
        {
            return __htmlURL[thePage];
        }

        // build the htmlURLs
        if (!window.__htmlURL)
        {
            c_page = 0;
            __htmlURL=[];
            for (var i=0;i<$_('comicShow').options.length;++i)
            {
                __htmlURL.push(cfg_host_base()+'\/comic_show\/c'+$('#c').val()+'_m'+$("#m").val()+'_i'+$_('comicShow').options[i].value+'.html');
                if ($_('comicShow').options[i].selected)
                    c_page=i;
            }
        }
    }else if (window.location.href.indexOf("www.boston.com/bigpicture")!==-1)
    {
        VerticalWritting = false;
        Landscape = true;

        if (!window.__imgs)
        {
            c_page = 0;
            __imgs=[];
            bpDivs = document.getElementsByClassName("bpBoth");
            for (var i=0; i<bpDivs.length;++i)
            {
                __imgs.push(
                    {
                    url:bpDivs[i].getElementsByClassName("bpImage")[0].src, 
                    photoNum:bpDivs[i].getElementsByClassName("photoNum")[0].innerText,
                    caption:bpDivs[i].getElementsByClassName("bpCaption")[0].childNodes[1].nodeValue 
                });
            }
        }

        var getCurrentPage=function()
        {
            return c_page;
        }
        var getPageCount=function()
        {
            return __imgs.length;
        }
        var getImgURL=function(thePage)
        {
            return __imgs[thePage].url;
        }
        var setCurrentPage=function(thePage)
        {
            c_page=thePage;
        }

        div_postprocess = function(theDivImg)
        {
            theDivImg.appendChild(document.createElement("br"));
            theDivImg.appendChild(document.createTextNode(__imgs[theDivImg.page].caption));
            theDivImg.loadImg=function()
            {
                var _this=this;
                this.tImg.onload=function()
                {
                    var _w=this.width;
                    var _h=this.height;
                    if (_this.scrollHeight>690)
                    {
                        this.height=this.height - (_this.scrollHeight-690);
                        this.width=Math.floor(_w*this.height/_h);
                    }
                    this.onload=null;
                };
                setTimeout(function() {
                    if (!_this.tImg.flink)
                        _this.tImg.flink=getImgURL(_this.page);
                    _this.tImg.src=_this.tImg.flink;
                } ,0);
                // this.className="bpCaption";
                // this.tImg.style.position="relative";
                // this.tImg.style.top="0px";
                // this.tImg.style.left="0px";
            };
        };

    }
    else {
        return;
    }
    if (!window.__iPadReaderInitialized)
    {
        // window.__iPadReaderInitialized = true;
        // push the pages to the
        for (var i=0;i<getPageCount();++i)
        {
            history.pushState(i,"Page "+(i+1), getPageURL(i));
        }
        window.onpopstate=function(e)
        {
            c_page=e.state;
            div_imgs[c_page].focusMe();
        };
    }

    


    // clear the images for more memory
    var emptyImageSrc="";
    var imgs = document.getElementsByTagName("img");
    for(var i=0;i<imgs.length;++i)
        imgs[i].src = emptyImageSrc;

    setTimeout(function(){

        if (/iPod|iPhone/.test(navigator.userAgent))
        {
            m.content="width=device-width,initial-scale=1.0,maximum-scale=1.5,minimum-scale=0.25";
            document.getElementsByTagName("head")[0].appendChild(m);
            document.body.innerHTML="";
            for(i=0; i<getPageCount(); ++i)
            {
                var div_img=document.createElement("div");
                div_img.style.cssText="display:none;position:absolute;left:0px;top:0px;"
                div_img.page=i;
                div_img.tImg=new Image();
                div_img.tImg.style.cssText="position:absolute;left:0px;top:0px;";
                div_img.appendChild(div_img.tImg);
                div_img.unloaded=true;
                div_img.eraseImg=function()
                {
                    if(!this.unloaded)
                    {
                        this.unloaded=true;
                        this.tImg.src=emptyImageSrc;
                    };
                };
                div_img.loadImg=function(focus)
                {
                    var _this=this;
                    var scrollToPos=function ()
                    {
                        if (VerticalWritting)
                        {
                            setTimeout(function(){ window.scrollTo(_this.tImg.width-innerWidth,0); },0);
                        } else
                        {
                            setTimeout(function(){ window.scrollTo(0,0); },0);
                        }

                    }
                    if(!this.unloaded)
                    {
                        if (focus)
                            scrollToPos();
                        return;
                    }
                    this.unloaded=false;
                    this.tImg.onload=function(){
                        if (focus)
                            scrollToPos();
                        this.onload=null;
                    }
                    setTimeout(function() {
                        if (!_this.tImg.flink)
                            _this.tImg.flink=getImgURL(_this.page);
                        _this.tImg.src=_this.tImg.flink;
                    } ,0);
                };
                div_img.focusMe=function()
                {
                    setCurrentPage(this.page);
                    div_imgs[this.page].style.display="inline";
                    div_imgs[this.page].loadImg(true);
                    for (var i=this.page+1; i<div_imgs.length;++i)
                    {
                        div_imgs[i].style.display="none";
                        if(i>this.page+3)
                            div_imgs[i].eraseImg();
                        else 
                            div_imgs[i].loadImg(false);
                    }
                    for (var i=this.page-1; i>=0;--i)
                    {
                        div_imgs[i].style.display="none";
                        if(i<this.page-2)
                            div_imgs[i].eraseImg();
                        else 
                            div_imgs[i].loadImg(false);
                    }
                };
                document.body.appendChild(div_img);
                div_imgs.push(div_img);
            };
            var nextImg=function()
            {
                ++c_page;
                if(c_page>=div_imgs.length)
                {
                    c_page=div_imgs.length-1;
                    alert("Last page already");
                }else 
                    history.forward();
                    // div_imgs[c_page].focusMe();
            };
            var preImg=function()
            {
                --c_page;
                if(c_page<0)
                {
                    c_page=0;
                    alert("First page already");
                }else 
                {
                    history.back();
                    // div_imgs[c_page].focusMe();
                }
            };
            document.onmouseup=function(e) {

                if (VerticalWritting)
                {
                    if (e.offsetX-scrollX < innerWidth/2)
                        nextImg();
                    else
                        preImg();
                } else
                {
                    if (e.offsetX-scrollX > innerWidth/2)
                        nextImg();
                    else
                        preImg();
                }
            };
        }else
        {

            if (Landscape)
            {
                var __ScreenWidth = 1024;
                var __ScreenHeight= 690;
            } else
            {
                var __ScreenWidth = 768;
                var __ScreenHeight = 946;
            }
            m.content="user-scalable=no,width=device-width,initial-scale=1.0,maximum-scale=1.0";
            document.getElementsByTagName("head")[0].appendChild(m);
            document.body.innerHTML="<div id=\"main\" style=\"width:"+__ScreenWidth+"px;height:"+__ScreenHeight+"px;overflow:hidden;position:absolute;\">";
            for(i=0; i<getPageCount(); ++i)
            {
                var div_img=document.createElement("div");
                div_img.style.cssText="visibility:hidden;position:absolute;left:0px;top:0px;width:"+__ScreenWidth+"px;height:"+__ScreenHeight+"px;overflow-x:hidden;overflow-y:hidden;"
                div_img.page=i;
                div_img.tImg=new Image();
                div_img.appendChild(div_img.tImg);
                div_img.unloaded=true;
                div_img.eraseImg=function()
                {
                    if(!this.unloaded)
                    {
                        this.unloaded=true;
                        this.tImg.src=emptyImageSrc;
                    };
                };
                div_img.loadImg=function()
                {
                    var _this=this;
                    if(!this.unloaded)
                    {
                        if (!this.tImg.onload)
                        {
                            if (this.setToRight ^ !VerticalWritting)
                                this.tImg.style.left=this.tImg.width<=__ScreenWidth?(__ScreenWidth-this.tImg.width)/2+"px":"0px";
                            else
                                this.tImg.style.left=this.tImg.width<=__ScreenWidth?(__ScreenWidth-this.tImg.width)/2+"px":__ScreenWidth-this.tImg.width+"px";
                        }
                        return;
                    }
                    this.unloaded=false;
                    this.tImg.onload=function()
                    {
                        var _w=this.width;
                        var _h=this.height;
                        if(_h>__ScreenHeight)
                        {
                            this.height=__ScreenHeight;
                            this.width=Math.floor(_w*__ScreenHeight/_h);
                        };
                        if (this.height<10){
                            this.tImg.style.top="0px";
                            this.tImg.style.left="0px";
                        } else{
                            if (_this.setToRight ^ !VerticalWritting)
                                this.style.left=this.width<=__ScreenWidth?(__ScreenWidth-this.width)/2+"px":"0px";
                            else
                                this.style.left=this.width<=__ScreenWidth?(__ScreenWidth-this.width)/2+"px":__ScreenWidth-this.width+"px";
                            this.style.top =(__ScreenHeight - this.height)/2 + "px";
                        }
                        this.onload=null;
                    };
                    setTimeout(function() {
                        if (!_this.tImg.flink)
                            _this.tImg.flink=getImgURL(_this.page);
                        _this.tImg.src=_this.tImg.flink;
                    } ,0);
                    this.tImg.style.position="absolute";
                    this.tImg.style.top="0px";
                    this.tImg.style.left="0px";
                };
                div_img.focusMe=function(setToRight)
                {
                    setCurrentPage(this.page);
                    div_imgs[this.page].style.visibility="visible";
                    div_imgs[this.page].setToRight = setToRight;
                    div_imgs[this.page].loadImg(true);
                    for (var i=this.page+1; i<div_imgs.length;++i)
                    {
                        div_imgs[i].style.visibility="hidden";
                        div_imgs[i].setToRight = false
                        if(i>this.page+3)
                            div_imgs[i].eraseImg();
                        else 
                            div_imgs[i].loadImg(false);
                    }
                    for (var i=this.page-1; i>=0;--i)
                    {
                        div_imgs[i].style.visibility="hidden";
                        div_imgs[i].setToRight = false
                        if(i<this.page-2)
                            div_imgs[i].eraseImg();
                        else 
                            div_imgs[i].loadImg(false);
                    }
                };
                div_postprocess(div_img);
                $_("main").appendChild(div_img);
                div_imgs.push(div_img);
            };
            var slideTowardRight=function()
            {
                if(parseInt(div_imgs[c_page].tImg.style.left)<0)
                {
                    var t_page = c_page;
                    div_imgs[c_page].tImg.style.left="0px";
                    div_imgs[c_page].tImg.style.webkitTransitionDuration="500ms";
                    onwebkittransitionend=function(){
                        onwebkittransitionend=null;
                        div_imgs[t_page].tImg.style.webkitTransitionDuration=0;
                    }
                    return true;
                };
                return false;
            };
            var slideTowardLeft=function()
            {
                if(div_imgs[c_page].tImg.width>__ScreenWidth && div_imgs[c_page].tImg.style.left=="0px")
                {
                    var t_page = c_page;
                    div_imgs[c_page].tImg.style.left=__ScreenWidth-div_imgs[c_page].tImg.width+"px";
                    div_imgs[c_page].tImg.style.webkitTransitionDuration="500ms";
                    onwebkittransitionend=function(){
                        onwebkittransitionend=null;
                        div_imgs[t_page].tImg.style.webkitTransitionDuration=0;
                    }
                    return true;
                }
                return false;
            }

            var preImg=function()
            {

                if (VerticalWritting)
                {
                    if (slideTowardLeft())
                        return;
                } else
                {
                    if (slideTowardRight())
                        return;
                }
                --c_page;
                if(c_page<0)
                {
                    c_page=0;
                    alert("First page already");
                }else 
                {
                    // div_imgs[c_page].focusMe(true);
                    history.back();
                }
            };
            var nextImg=function()
            {
                if (VerticalWritting)
                {
                    if (slideTowardRight())
                        return;
                } else
                {
                    if (slideTowardLeft())
                        return;
                }
                ++c_page;
                if(c_page>=div_imgs.length)
                {
                    c_page=div_imgs.length-1;
                    alert("Last page already");
                }else 
                    history.forward();
                    // div_imgs[c_page].focusMe();
            };
            if(navigator.userAgent.indexOf("iPad")!=-1)
            {
                document.ontouchstart=function(e) {
                    clickAt(e.touches[0].pageX);
                    return false;
                };
            }
            else
            {
                document.onmousedown=function(e) {
                    clickAt(e.pageX);
                };
            };
            var clickAt=function(x)
            {
                if (VerticalWritting)
                {
                    if(x<__ScreenWidth/2)
                        nextImg();
                    else 
                        preImg();
                } else{
                    if(x>__ScreenWidth/2)
                        nextImg();
                    else 
                        preImg();
                }
            };
        }

        c_page=getCurrentPage();

        if (!window.__iPadReaderInitialized)
        {
            window.__iPadReaderInitialized = true;
            var pageDelta = c_page - (getPageCount() -1);
            if (pageDelta != 0)
                history.go(pageDelta)
            else
                div_imgs[c_page].focusMe();
        }else
            div_imgs[c_page].focusMe();
    },0);
})();
